﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using KPIS.Utils;
using KPIS.GERP.GHRMS.BLL;
using KPIS.GERP.GHRMS.IBLL;
using KPIS.GERP.GHRMS.MODEL;
using System.Web.UI.WebControls;
using KPIS.GERP.GHRMS.APP.Classes;
using Telerik.Web.UI;

namespace KPIS.GERP.GHRMS.APP.App_UI.Forms
{
    public partial class HRMJobSpecList : System.Web.UI.Page
    {
        private SsMng ssMng = new SsMng();
        private Main main = new Main();
        private SsMng creatby = new SsMng();
        private IHRMJobSpecListBLL CreateJobSpecList = new HRMJobSpecListBLL();
        private IPositionBLL posBLL = new PositionBLL();
        private IJobSiteBLL jobsiteBLL = new JobSiteBLL();
        private IEmployeeTypeBLL emptypeBLL = new EmployeeTypeBLL();
        private IPositionTypeBLL postypeBLL = new PositionTypeBLL();
        private IFieldBLL fieldBLL = new FieldBLL();
        private IExecutiveBLL execBLL = new ExecutiveBLL();
        private IClassSpecificationBLL specBLL = new ClassSpecificationBLL();
        private PositionExtraBLL extBLL = new PositionExtraBLL();


        private JobSiteInfo jobsiteInfo = new JobSiteInfo();
        private ITreeViewBLL treeBLL = new TreeViewBLL();

        private int idJobSiteSeqRoot = 1;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                FillDataToEmpType();

                ChangeMode(Main.EditMode.View);
                Session["update"] = Server.UrlEncode(System.DateTime.Now.ToString());
            }
        }

        protected void dgtJobSpecCtrl_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
        {
             string intJobSpacSeq =lblJobSpecSeq.Text; //Seq ของJobSpac
             string strPosSeq = lblPosSeq.Text; //Seq ของตำแหน่ง

             dgtJobSpecCtrl.DataSource = CreateJobSpecList.Search(intJobSpacSeq, strPosSeq, null);
         }

        protected void dgtJobSpecCtrl_ItemCommand(object source, GridCommandEventArgs e)
         {
             string JobSite = RadTreeView1.SelectedValue.Length <= 0 ? "" : RadTreeView1.SelectedValue;

             if (e.CommandName == "Delete")
             {
                 int seq = Convert.ToInt32((e.Item as GridDataItem).OwnerTableView.DataKeyValues[e.Item.ItemIndex]["pos_seq"]);
                 posBLL.Delete(seq, ssMng.EmpSeqI);
             }
             else if (e.CommandName == "GridEdit")
             {
                 ChangeMode(Main.EditMode.Edit);

                 GridDataItem item = (GridDataItem)e.Item;

                 txtSpecDetail.Text = item["spec_detail"].Text;
                 lblJobSpecSeq.Text = item["job_spec_seq"].Text;
             }
             else if (e.CommandName == "GridDelete")
             {
                 GridDataItem item = (GridDataItem)e.Item;

                 string intJobSpacSeq = item["job_spec_seq"].Text;
                 CreateJobSpecList.Delete(intJobSpacSeq, creatby.EmpSeqI);

                 LoadJobSpecCtrl();
             }
         }

        private void LoadJobSpecCtrl()
        {
            BindDataControl();
            string intJobSpacSeq = lblJobSpecSeq.Text; //Seq ของJobSpac
            string strPosSeq = lblPosSeq.Text; //Seq ของตำแหน่ง
            string strSpecDetail = txtSpecDetail.Text; // รายละเอียดของคุณสมบัติตำแหน่่ง

            dgtJobSpecCtrl.DataSource = CreateJobSpecList.Search(intJobSpacSeq, strPosSeq, null);
            dgtJobSpecCtrl.DataBind();
        }

        protected void Page_PreRender(object sender, EventArgs e)
        {
            ViewState["update"] = Session["update"];
        }

        public void LoadDataGrid(string JobSite)
        {
        }

        private void LoadDataGrid()
        {
            try
            {
                Nullable<int> PosSeq = string.IsNullOrEmpty(lblPosSeq.Text) ? (int?)null : Convert.ToInt32(lblPosSeq.Text.Trim());
                DataSet ds = extBLL.LoadPositionExtra((int?)null, PosSeq, (int?)null);
            }
            catch (Exception ex)
            {
                Web.ShowAlert(this, ex.Message);
            }
        }

       private void ChangeMode(Main.EditMode mode)
        {
            switch (mode)
            {
                case Main.EditMode.AddNew:
                    dgtJobSpecCtrl.Visible = false;
                    Save_Edit.Visible = false;
                    Save_AddNew.Visible = true;
                    ShowGrid.Visible = true;
                    AddNew.Visible = false;
                    Delete.Visible = false;
                    PanelGrid.Visible = false;
                    PanelDetail.Visible = true;
                    panelCommand.Visible = true;
                break;

                case Main.EditMode.View:
                    dgtJobSpecCtrl.Visible = false;
                    Save_Edit.Visible = false;
                    Save_AddNew.Visible = false;
                    ShowGrid.Visible = false;
                    AddNew.Visible = false;
                    Delete.Visible = false;
                    PanelGrid.Visible = false;
                    PanelDetail.Visible = false;
                    panelCommand.Visible = false;
                break;

                case Main.EditMode.ShowGrid:
                    dgtJobSpecCtrl.Visible = true;
                    Save_Edit.Visible = false;
                    Save_AddNew.Visible = false;
                    ShowGrid.Visible = true;
                    AddNew.Visible = true;
                    PanelGrid.Visible = true;
                    Delete.Visible = true;
                    PanelDetail.Visible = false;
                    panelCommand.Visible = true;
                break;

                case Main.EditMode.Edit:
                    dgtJobSpecCtrl.Visible = false;
                    Save_Edit.Visible = true;
                    Save_AddNew.Visible = false;
                    ShowGrid.Visible = true;
                    AddNew.Visible = false;
                    Delete.Visible = false;
                    PanelGrid.Visible = false;
                    PanelDetail.Visible = true;
                    panelCommand.Visible = true;
                break;
            }
        }

        private void ClearControlData()
        {
            txtSpecDetail.Text = "";
        }

        private void BindTree(RadTreeView treeView)
        {
            Nullable<int> EmpTypeSeq = cmbEmpType.SelectedValue.Length > 0 ? Int32.Parse(cmbEmpType.SelectedValue) : (int?)null;
            IList<TreeViewInfo> infoList = posBLL.LoadPositionJobsites(EmpTypeSeq, "");
            treeView.DataSource = infoList;
            treeView.DataBind();
        }
  
        private void LoadRootNodes(RadTreeView treeView, TreeNodeExpandMode expandMode)
        {
            Nullable<int> EmpTypeSeq = cmbEmpType.SelectedValue.Length > 0 ? Int32.Parse(cmbEmpType.SelectedValue) : (int?)null;

            treeView.Nodes.Clear();

            foreach (TreeViewInfo info in posBLL.LoadPositionJobsites(EmpTypeSeq, ""))
            {
                RadTreeNode node = new RadTreeNode();
                node.Text = info.Name;//  info.Id.Split('-').Count() > 1 ? info.Name : String.Format("{0} : {1}", info.Id, info.Name);
                node.ToolTip = info.Descr;
                node.Value = info.Id;
                node.ImageUrl = info.Image_url;
                if (Convert.ToInt32(info.Children_count) > 0)
                {
                    node.ExpandMode = expandMode;
                }
                treeView.Nodes.Add(node);
            }  

            //treeView.ExpandAllNodes();
        }

        private void PopulateNodeOnDemand(RadTreeNodeEventArgs e, TreeNodeExpandMode expandMode)
        {
            e.Node.Dispose();
            e.Node.Nodes.Clear();

            Nullable<int> EmpType = string.IsNullOrEmpty(cmbEmpType.SelectedValue) ? (int?)null : Int32.Parse(cmbEmpType.SelectedValue);

            int childNode = 0;

            foreach (TreeViewInfo info in posBLL.LoadPositionJobsites(EmpType, e.Node.Value))
            {
                RadTreeNode node = new RadTreeNode();
                node.Text = info.Name; 
                node.ToolTip = info.Descr;
                node.Value = info.Id;
                node.ImageUrl = info.Image_url;
                childNode = info.Children_count;
                if (Convert.ToInt32(info.Children_count) > 0)
                {
                    node.ExpandMode = expandMode;
                }
                e.Node.Nodes.Add(node);
            }
            if (childNode > 0)
            {
                e.Node.Expanded = true;
                e.Node.ExpandMode = expandMode;
            }

            // e.Node.ExpandChildNodes();
        }

        protected void cmdSearch_Click(object sender, ImageClickEventArgs e)
        {
            RadTreeNodeCollection nodes = this.RadTreeView1.Nodes;
            string strSearch = txtSearch.Text.TrimEnd();
    
            foreach (RadTreeNode n in nodes)
            {
                n.BackColor = RadTreeView1.BackColor;
                main.ClearRecursive(n, RadTreeView1.BackColor);
            }

            foreach (RadTreeNode n in nodes)
            {
                if (strSearch.Length > 0)
                {
                    if (n.Text.IndexOf(strSearch) >= 0)
                    {
                        n.BackColor = System.Drawing.Color.Yellow;
                        n.ExpandParentNodes();
                    }
                    main.FindRecursive(n, strSearch);
                }
            }
        }

        private void ExpandByPath(string fullPath, ref RadTreeView radTreeView)
        {
            radTreeView.CollapseAllNodes();

            foreach (string path in fullPath.Split('/'))
            {
                if (!String.IsNullOrEmpty(path))
                {
                    var node = RadTreeView1.FindNodeByValue(path);
                    if (node != null)
                    {
                        PopulateNodeOnDemand(new RadTreeNodeEventArgs(node), TreeNodeExpandMode.ServerSide);
                        if (node.ParentNode != null)
                            node.ParentNode.Expanded = true;
                    }
                }
            }
        }

        protected void cmbEmpType_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            Session["EMP_TYPE_SEQ"] = cmbEmpType.SelectedValue;
            LoadRootNodes(RadTreeView1, TreeNodeExpandMode.ServerSideCallBack);
            LoadDataGrid(RadTreeView1.SelectedValue);

            ChangeMode(Main.EditMode.View);
        }

        protected void cmdExpand_Click(object sender, ImageClickEventArgs e)
        {
            RadTreeView1.ExpandAllNodes();
        }

        protected void cmdCollapse_Click(object sender, ImageClickEventArgs e)
        {
            RadTreeView1.CollapseAllNodes();
        }
        protected void RadTreeView1_NodeExpand(object sender, RadTreeNodeEventArgs e)
        {
            PopulateNodeOnDemand(e, TreeNodeExpandMode.ServerSideCallBack);
        }
        public void RefreshTreeAddNew()
        {
            LoadRootNodes(RadTreeView1, TreeNodeExpandMode.ServerSideCallBack);
        }

        protected void RadTreeView1_NodeClick(object sender, RadTreeNodeEventArgs e)
        {
            RadTreeNode selected_node = RadTreeView1.SelectedNode;

            string value = selected_node.Value;
            string name = selected_node.Text.Trim();
            string[] root_value = value.Split(new string[] { "-" }, StringSplitOptions.None);
            int nCount = root_value.Length;
            Session["TreeNodeValue"] = value;
            Session["TreeNodeSelect"] = value;
            if (!string.IsNullOrEmpty(value))
            {
                if (nCount > 1)
                {
                    lblPosSeq.Text = root_value[1];
                    Session["TreeNodeValue"] = root_value[1];
                    Session["POS_SEQ"] = Session["TreeNodeValue"].ToString();

                    CheckLabelName();
                    LoadJobSpecCtrl();
                    ChangeMode(Main.EditMode.ShowGrid);
                }
                else
                {
                    ChangeMode(Main.EditMode.View);
                }
            }
        }

        public void FillDataToEmpType()
        {
            IList<EmployeeTypeInfo> InfoList = emptypeBLL.ListEmployeeTypes(null);

            cmbEmpType.DataSource = InfoList;
            cmbEmpType.DataBind();
        }

        public void FillDataToExecPositions()
        {
            IList<ExecutiveInfo> InfoList = execBLL.ListExecutives(null, SystemInfo._ActiveRecordStatus);
        }

        public void FillDataToUpperPos(Nullable<int> nPosSeq)
        {
            DataSet ds = posBLL.LoadPositions((int?)null, 1, (int?)null, "");
            DataTable dt = new DataTable();
            if (ds.Tables.Count > 0)
            {
                dt = ds.Tables[0];
            }
        }

        protected void FillDataToJobSite()
        {
            JobSiteTypeInfo Info = new JobSiteTypeInfo();
            DataSet ds = jobsiteBLL.LoadJobSites("", SystemInfo._JobsiteExternal, "", "");
            DataTable dt = new DataTable();
            if (ds.Tables.Count > 0)
            {
                dt = ds.Tables[0];
            }
        }

        private void BindDataControl()
        {
            FillDataToEmpType();
            FillDataToExecPositions();
            FillDataToUpperPos(1);
            FillDataToJobSite();
            int Sequence = Session["TreeNodeValue"].ToString().Length > 0 ? Int32.Parse(Session["TreeNodeValue"].ToString()) : idJobSiteSeqRoot;

            DataSet ds = posBLL.LoadPositions(Sequence, (int?)null, (int?)null, "");
            DataRowCollection drc;

            if (ds.Tables.Count > 0)
            {
                drc = ds.Tables[0].Rows;
                if (drc.Count > 0)
                {
                    lblPosSeq.Text = drc[0]["POS_SEQ"].ToString();
                    cmbEmpType.SelectedValue = drc[0]["EMP_TYPE_SEQ"].ToString();
                }
            }
        }

        private void LoadDetail()
        {
            int Sequence = Session["TreeNodeValue"].ToString().Length > 0 ? Int32.Parse(Session["TreeNodeValue"].ToString()) : idJobSiteSeqRoot;
            DataSet ds = posBLL.LoadPositions(Sequence, (int?)null, (int?)null, "");
            
            DataRowCollection drc;

            if (ds.Tables.Count > 0)
            {
                drc = ds.Tables[0].Rows;
                if (drc.Count > 0)
                {
                    lblPosSeq.Text = drc[0]["POS_SEQ"].ToString();
                    lblPosRef.Text = drc[0]["POS_REF"].ToString();
                }
            }
        }

        protected void ShowGrid_Click(object sender, EventArgs e)
        {
            LoadJobSpecCtrl();
            ChangeMode(Main.EditMode.ShowGrid);
        }

        protected void AddNew_Click(object sender, EventArgs e)
        {
            ChangeMode(Main.EditMode.AddNew);
            ClearControlData();
        }

        protected void Save_AddNew_Click(object sender, EventArgs e)
        {
            string PosSeq = lblPosSeq.Text;
            string strSpecDetail = txtSpecDetail.Text;
            string intJobSpacSeq = lblJobSpecSeq.Text;
            if (!CheckNullValue())
            {
                return;
            }

            bool CheckValueSubmit = CreateJobSpecList.CheckValueSubmit(intJobSpacSeq);

            if (CheckValueSubmit == true)
            {
                CreateJobSpecList.Insert(PosSeq, strSpecDetail, creatby.EmpSeqI);

                main.MessageAlert(Page, "บันทึกข้อมูลเรียบร้อยแล้ว");
                ClearControlData();
                LoadJobSpecCtrl();
                ChangeMode(Main.EditMode.ShowGrid);
            }
            else
            {
                main.MessageAlert(Page, "ตรวจสอบข้อมูลอีกครั้ง");
            }
        }

        protected void Save_Edit_Click(object sender, EventArgs e)
        {
            string strSpecDetail = txtSpecDetail.Text;
            string intJobSpacSeq = lblJobSpecSeq.Text;
            if (!CheckNullValue())
            {
                return;
            }

            bool CheckValueSubmit = CreateJobSpecList.CheckValueSubmit(intJobSpacSeq);

            if (CheckValueSubmit == true)
            {
                CreateJobSpecList.Update(strSpecDetail, intJobSpacSeq, creatby.EmpSeqI);

                main.MessageAlert(Page, "แก้ไขข้อมูลเรียบร้อยแล้ว");
                LoadJobSpecCtrl();
                ChangeMode(Main.EditMode.ShowGrid);
            }
            else
            {
                main.MessageAlert(Page, "ตรวจสอบข้อมูลอีกครั้ง");
            }
        }

        protected void Delete_Click(object sender, EventArgs e)
        {
            if (PanelGrid.Visible == true)
            {
                foreach (GridDataItem item in dgtJobSpecCtrl.SelectedItems)
                {
                    string intJobSpacSeq = item["job_spec_seq"].Text;
                    CreateJobSpecList.Delete(intJobSpacSeq, creatby.EmpSeqI);

                    LoadJobSpecCtrl();
                }
            }
        }

        protected void lbnAddNew_Click(object sender, EventArgs e)
        {
            ChangeMode(Main.EditMode.AddNew);
        }

        private void CheckLabelName()
        {
            string LoadNamePos = "";
            string strPosSeq = lblPosSeq.Text;
            LoadNamePos = CreateJobSpecList.LoadNamePos(strPosSeq);
            lblNamePos.Text = LoadNamePos;
        }

        private bool CheckNullValue()
        {
            bool bOk = true;

            if (txtSpecDetail.Text == "")
            {
                main.MessageAlert(Page, "กรุณากรอกคุณสมบัติ");
                bOk = false;
            }
            return bOk;
        }
    }
}